#include "MaterialGraphLinkView.h"

#include "Widgets/CanvasWidget.h"
#include "MaterialGraphLinkViewModel.h"

void RMaterialGraphLinkView::BindViewModel(TSharedObjectPtr<RMaterialGraphLinkViewModel> InModel)
{
    BaseViewModel=InModel;
}

void RMaterialGraphLinkView::CreateWidget(TSharedObjectPtr<RWidget> InGrapgWidget)
{
    auto Root=NewWidget<RWidget>(InGrapgWidget);
    Root->Anchor.Fill(InGrapgWidget);
    Root->Visible=[this](){
        return !BaseViewModel->IsHidden();
    };

    auto Canvas=NewWidget<RCanvasWidget>(Root);
    RCanvasWidgetWeakPtr WeakCanvas=Canvas;
    Canvas->Anchor.Fill(Root);
    Canvas->OnPaint.BindLambda([this,WeakCanvas](){
        WeakCanvas->Clear();
        SVec2 Start,End;
        Start.X=BaseViewModel->GetStartXInGraphSpace();
        Start.Y=BaseViewModel->GetStartYInGraphSpace();
        End.X=BaseViewModel->GetEndXInGraphSpace();
        End.Y=BaseViewModel->GetEndYInGraphSpace();
        
        SVec2 WidgetCenter=WeakCanvas->PresentSize*0.5f;
        Start+=WidgetCenter;
        End+=WidgetCenter;

        auto Points= BaseViewModel->CalculateLinkingPoints(Start,End);
        
        for(int64_t Index=0; Index<Points.Num()-1; Index++)
        {
            SColor Color;
            if(Index<Points.Num()*0.5f)
            {
                Color=BaseViewModel->GetStartColor();
            }
            else
            {
                Color=BaseViewModel->GetEndColor();
            }

            WeakCanvas->AddLine(
                Points[Index],Points[Index+1]
                ,5
                ,Color);
        }
    
    });
}